package com.daisuxia.web.controller;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.service.IRiskCreditUserService;
import com.daisuxia.risk.utils.yx.RC4_128_V2;
import com.daisuxia.risk.utils.yx.YxLoanRecords;
import com.daisuxia.risk.utils.yx.YxRiskResults;
import com.daisuxia.risk.utils.yx.YxSend;
import com.daisuxia.risk.utils.yx.YxSendData;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JSONUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("yx/")
public class YxController extends BaseController {
	Logger logger = LoggerFactory.getLogger(getClass());
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyMMdd");
	@Autowired
	private IUserService userService;
	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IRiskCreditUserService riskCreditUserService;

	@RequestMapping(value = "queryData", method = RequestMethod.POST)
	public void queryData(HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject result = new JSONObject();
		String msg = "出现系统错误 ,需要检查错误日志";
		String code = "5000";
		String encParams = "";
		try {
			String params = request.getParameter("params");
			logger.info("yx query data recive" + params);
			if (params != null) {
				JSONObject jsonObject = JSONObject.fromObject(params);
				if (jsonObject.containsKey("params")) {
					params = jsonObject.getString("params");
					LinkedHashMap<String, String> map2 = SysCacheUtils
							.getConfigParams(BackConfigParams.YX);

					String pwd = map2.get("YX_KEY");
					String desParams = RC4_128_V2.decode(URLDecoder
							.decode(params), pwd);
					if (StringUtils.isNotBlank(desParams)) {
						JSONObject jsonObject2 = JSONObject
								.fromObject(desParams);
						JSONObject jsonObject3 = jsonObject2
								.getJSONObject("data");
						String cardNum = jsonObject3.getString("idNo");
						String userName = jsonObject3.getString("name");
						YxSend yxSend = new YxSend();
						YxSendData yxSendData = new YxSendData();
						List<YxLoanRecords> list2 = new ArrayList<YxLoanRecords>();
						List<YxRiskResults> list3 = new ArrayList<YxRiskResults>();
						User user = userService.searchByUserIDCard(cardNum);
						if (null!=user && "1".equals(user.getRealnameStatus())) {
							if (userName.equals(user.getRealname())) {
								// 查询借款信息
								List<BorrowOrder> list = borrowOrderService
										.findByUserId(Integer.valueOf(user
												.getId()));
								if (list != null && list.size() > 0) {
									// 查询征信信息中的黑名单信息
									for (BorrowOrder borrow : list) {
										int status = borrow.getStatus()
												.intValue();
										String loanDate = null;
										String approvalStatusCode = null;
										//未放款按申请时间算
										if(BorrowOrder.STATUS_CSBH==status||BorrowOrder.STATUS_FSBH==status||BorrowOrder.STATUS_FSTG==status||BorrowOrder.STATUS_FKBH==status||BorrowOrder.STATUS_FKZ==status||BorrowOrder.STATUS_FKSB==status) 
											loanDate=sdf.format(borrow.getOrderTime());
										else {
											approvalStatusCode="202";//已放款
											//放款按照放款时间算
											loanDate=sdf.format(borrow.getVerifyLoanTime());
										}
										//----------------------------审核结果-----------------------------
										if(BorrowOrder.STATUS_DCS==status||BorrowOrder.STATUS_CSTG==status||BorrowOrder.STATUS_FSTG==status||BorrowOrder.STATUS_FKZ==status) 
											approvalStatusCode="201";//审核中
										else if(BorrowOrder.STATUS_CSBH==status||BorrowOrder.STATUS_FSBH==status||BorrowOrder.STATUS_FKBH==status)
											approvalStatusCode="203";//拒贷
										YxLoanRecords yxLoanRecords = new YxLoanRecords();
										yxLoanRecords.setName(userName);
										yxLoanRecords.setCertNo(cardNum);
										yxLoanRecords.setLoanDate(loanDate);
										yxLoanRecords.setPeriods("1");
										int money = borrow.getIntoMoney() / 100;
										String amount = "";
										if (money < 1000) {
											amount = "(0,1000]";
										} else if (money < 5000) {
											amount = "(1000,5000]";
										} else if (money < 10000) {
											amount = "(5000,10000]";
										} else if (money < 20000) {
											amount = "(10000,20000]";
										} else if (money < 50000) {
											amount = "(20000,50000]";
										} else if (money < 100000) {
											amount = "(50000,100000]";
										} else {
											amount = "(100000,+]";
										}
										yxLoanRecords.setLoanAmount(amount);
										yxLoanRecords
												.setApprovalStatusCode(approvalStatusCode);
										String loanStatusCode = null;
										if (status == 21) {
											loanStatusCode = "301";
										} else if (status == 30 || status == 34) {
											loanStatusCode = "303";
										} else if (status == -11) {
											loanStatusCode = "302";
										}
										yxLoanRecords
												.setLoanStatusCode(loanStatusCode);
										yxLoanRecords.setLoanTypeCode("21");
										String overdueAmount = null;
										String overdueStatus = null;
										Integer overdueTotal = null;
										Integer overdueM3 = null;
										Integer overdueM6 = null;
										if (status == -11) {
											List<Repayment> repayments = repaymentService
													.findAllByBorrowId(borrow
															.getId());
											if (repayments != null
													&& repayments.size() > 0) {
												Repayment repayment = repayments
														.get(0);
												Long overMoney = repayment
														.getRepaymentAmount()
														- repayment
																.getRepaymentedAmount()
														/ 100;
												if (overMoney < 1000) {
													overdueAmount = "(0,1000]";
												} else if (overMoney < 5000) {
													overdueAmount = "(1000,5000]";
												} else if (overMoney < 10000) {
													overdueAmount = "(5000,10000]";
												} else if (overMoney < 20000) {
													overdueAmount = "(10000,20000]";
												} else if (overMoney < 50000) {
													overdueAmount = "(20000,50000]";
												} else if (overMoney < 100000) {
													overdueAmount = "(50000,100000]";
												} else {
													overdueAmount = "(100000,+]";
												}
												int overDays = repayment
														.getLateDay();
												int month = overDays / 30;
												if (month <= 1) {
													overdueStatus = "M1";
												} else if (month <= 2) {
													overdueStatus = "M2";
												} else if (month <= 3) {
													overdueStatus = "M3";
													overdueM3 = 1;
												} else if (month <= 4) {
													overdueStatus = "M4";
												} else if (month <= 5) {
													overdueStatus = "M5";
												} else if (month <= 6) {
													overdueStatus = "M6";
												} else {
													overdueStatus = "M6+";
													overdueM6 = 1;
												}
											}
											overdueTotal = 1;
										}
										yxLoanRecords
												.setOverdueAmount(overdueAmount);
										yxLoanRecords
												.setOverdueStatus(overdueStatus);
										yxLoanRecords
												.setOverdueTotal(overdueTotal);
										yxLoanRecords.setOverdueM3(overdueM3);
										yxLoanRecords.setOverdueM6(overdueM6);
										list2.add(yxLoanRecords);
									}
									List<RiskCreditUser> risks = riskCreditUserService
											.findByUserId(Integer.valueOf(user
													.getId()));
									if (risks != null && risks.size() > 0) {
										for (RiskCreditUser riskCreditUser : risks) {
											YxRiskResults yxRiskResults = new YxRiskResults();
											yxRiskResults
													.setRiskItemTypeCode("101010");
											yxRiskResults
													.setRiskItemValue(cardNum);
											yxRiskResults
													.setRiskDetail("命中黑名单有逾期记录");
											yxRiskResults
													.setRiskTime(DateUtil
															.getDateFormat(
																	riskCreditUser
																			.getAddTime(),
																	"yyyy"));
											list3.add(yxRiskResults);
										}
									}
									msg = "成功";
									code = "0000";
								} else {
									code = "0001";
									msg = "查询成功但无数据";
								}
							} else {
								// 姓名身份证号码不匹配
								code = "0001";
								msg = "查询成功但无数据";
								logger.info("name is not match cardnum");
							}
						} else {
							// 未实名认证
							code = "0001";
							msg = "查询成功但无数据";
						}
						yxSendData.setLoanRecords(list2);
						yxSendData.setRiskResults(list3);
						yxSend.setData(yxSendData);
						encParams = URLEncoder.encode(RC4_128_V2.encode(
								JSONUtil.beanToJson(yxSend), pwd), "UTF-8");
					} else {
						msg = "参数解密出现异常！";
						code = "4002";
					}
				} else {
					msg = "参数错误！";
					code = "4200";
				}
			} else {
				msg = "参数错误！";
				code = "4200";
			}

		} catch (Exception e) {
			logger.error("queryData error ", e);
		} finally {
			result.put("message", msg);
			result.put("errorCode", code);
			result.put("params", encParams);
		}
		SpringUtils.renderJson(response, JSONUtil.beanToJson(result));
	}
}
